package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.lib.domain.Customer;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.domain.Product;
import com.rockcent.mall.lib.domain.ShoppingCart;
import com.rockcent.mall.lib.domain.enumclass.ProductStatus;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.CustomerRepository;
import com.rockcent.mall.lib.repository.MerchantProductRepository;
import com.rockcent.mall.lib.repository.ShoppingCartRepository;
import com.rockcent.mall.lib.repository.ShoppingCartRepositoryCustom;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import com.sun.tools.javac.util.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Created by zhangjh on 2016/10/12.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class ShoppingCartController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ShoppingCartController.class);
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private ShoppingCartRepository shoppingCartRepository;
    @Autowired
    private MerchantProductRepository merchantProductRepository;
    @Autowired
    private CustomerHelper customerHelper;

    /**
     *
     * @api {get} /api/v2/shopping_cart/list 获取购物车
     * @apiGroup shoppingCard
     * @apiVersion 1.0.0
     *
     * @apiParam {Sring} userToken 用户Token
     *
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {Integer} buyCount 购买数量
     * @apiSuccess {Decimal} sellPrice 售价
     * @apiSuccess {String} logoUrl logo图
     * @apiSuccess {String} channelSalesCode 渠道码
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *              {
     *              "merchantId": 4,
     *              "merchantName": null,
     *              "product": [
     *                            {
     *                              "id": 7,
     *                              "name": "自提-b2测试产品",
     *                              "buyCount": 2,
     *                              "sellPrice": 0.01,
     *                              "channelSalesCode": "23452452345",
     *                              "logoUrl": "/20160506/20160506193437xjzaTbmd.jpg"
     *                           }
     *                        ]
     *              },
     *              ...
     *             ]
     *  }
     */
    @RequestMapping(value = Routes.SHOPPING_CART_LIST, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult list( HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            //关联查询查所有数据
            List<MerchantShoppingCartDto> shoppingCartDtoList = shoppingCartRepository.getShoppingCart(customerDto.getId());

            Map<Long,ShoppingCartDto> map = new LinkedHashMap();

            shoppingCartDtoList.stream().forEach(dto -> {
                Long merchantId = dto.getMerchantId();
                ShoppingCartDto shoppingCartDto  =map.get(merchantId);

                ShoppingCartProductDto shoppingCartProductDto = new ShoppingCartProductDto();
                RBeanUtils.copyProperties(dto,shoppingCartProductDto);

                if(shoppingCartDto==null){
                    shoppingCartDto = new ShoppingCartDto();
                    shoppingCartDto.setMerchantId(merchantId);
                    shoppingCartDto.setMerchantName(dto.getMerchantName());

                    List list = shoppingCartDto.getProduct();
                    if(list == null){
                        list = new ArrayList();
                    }
                    list.add(shoppingCartProductDto);
                    shoppingCartDto.setProduct(list);

                    map.put(merchantId,shoppingCartDto);


                }else{
                    List list = shoppingCartDto.getProduct();
                    list.add(shoppingCartProductDto);

                    shoppingCartDto.setProduct(list);
                }
            });

            jr.setData( map.values());
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {post} /api/v2/shopping_cart/delete 删除购物车
     * @apiGroup shoppingCard
     * @apiVersion 1.0.0
     *
     * @apiParam {String} userToken 用户token
     * @apiParam {String} productId 产品ID ，多个产品id之间用&分开即可,eg. productId=1&2
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": true
     *  }
     *
     */
    @RequestMapping(value = Routes.SHOPPING_CART_DELETE, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete( String productId, HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (null ==  productId ){
                jr.remind("productId:"+Product.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            if (null == productId) {
                jr.errorParam("productId:" + Product.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            CustomerDto customerDto = customerHelper.getSession(request);
            String[] temp = productId.split("&");
            List productIds =  Arrays.asList(temp);
            Integer count = shoppingCartRepository.deleteByCustomerIdAndProductIds(customerDto.getId(), productIds);
            if (count <= 0) {
                jr.errorParam("操作不成功或商品已删除",log);
                return;
            }
            jr.setData(true);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {post} /api/v2/shopping_cart/update 更新购物车(如果是新的商品就添加，如果是已存在的商品就是修改)
     * @apiGroup shoppingCard
     * @apiVersion 1.0.0
     *
     * @apiParam{Integer} userToken 用户token
     * @apiParam{Integer} productId 产品Id
     * @apiParam{Integer} buyCount 购买数量
     * @apiParam{String} from 添加来源：PRODUCT(产品详情页)；SHOPPING_CART(购物车)
     * @apiParam{String} [shareCode] 用户分享码
     * @apiParam{String} [salesCode] 商户分销码
     * @apiParam{String} [channel] 渠道
     * @apiParam{String} [channelSaleCode] 渠道码
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {Integer} buyCount 购买数量
     * @apiSuccess {String} channel 渠道
     * @apiSuccess {Long} customerId 用户ID
     * @apiSuccess {Long} productId 产品ID
     * @apiSuccess {String} salesCode 分销码
     * @apiSuccess {String} shareCode 用户分享码
     * @apiSuccess {String} channelSalesCode 渠道码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *              "id": 8,
     *              "dateCreated": "2016-10-12 16:58:02",
     *              "lastUpdated": "2016-10-12 18:28:27",
     *              "version": 2,
     *              "buyCount": 7,
     *              "channel": "2",
     *              "customerId": 3,
     *              "productId": 9,
     *              "salesCode": "2",
     *              "shareCode": "2"
     *          }
     *  }
     *
     */
    @RequestMapping(value = Routes.SHOPPING_CART_UPDATE, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult update(ShoppingCart shoppingCart,String from, HttpServletRequest request) {
        RestDoing doing = jr -> {
            //获取用户信息
            CustomerDto customerDto = customerHelper.getSession(request);
            Long productId = shoppingCart.getProductId();
            if (null == productId) {
                jr.errorParam("productId:" + Product.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            Product product = merchantProductRepository.findByIdAndIsDelete(productId, Whether.NO);
            if (product == null || product.getMallId() != customerDto.getMallId() ) {
                jr.errorParam("product:" + Product.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }
            ProductStatus productStatus = product.getStatus();
            Date dateSelling = product.getDateSelling();
            if(productStatus!=null && ProductStatus.SELLING==productStatus && dateSelling!=null) {
                Date today = DateUtils.getCurrentDate();
                if(dateSelling.compareTo(today)==1) {
                    jr.remind("产品在预售中",log);
                    return;
                }
            }
            //获取购物车
            ShoppingCart oldShoppingCart = shoppingCartRepository.findByCustomerIdAndProductId(customerDto.getId(), productId);
            if (null == oldShoppingCart) {
                //新增新的购物车
                oldShoppingCart = new ShoppingCart();
                oldShoppingCart.setCustomerId(customerDto.getId());
                oldShoppingCart.setProductId(shoppingCart.getProductId());
                oldShoppingCart.setDateCreated(new Date());
                oldShoppingCart.setBuyCount(shoppingCart.getBuyCount());
                oldShoppingCart.setMallId(customerDto.getMallId());
                oldShoppingCart.setMerchantId(product.getMerchantId());

                oldShoppingCart.setShareCode(shoppingCart.getShareCode());
                oldShoppingCart.setSalesCode(shoppingCart.getSalesCode());
                oldShoppingCart.setChannelSalesCode(shoppingCart.getChannelSalesCode());
            }else {
                //更新购物车产品数量
                //已经存在的购物车
                if ("PRODUCT".equals(from)){
                    //如果是从产品详情页添加的，按增量添加
                    oldShoppingCart.setBuyCount(shoppingCart.getBuyCount() + oldShoppingCart.getBuyCount());
                }else if ("SHOPPING_CART".equals(from)){
                    //如果是从购物车修改的，按实际数值修改
                    oldShoppingCart.setBuyCount(shoppingCart.getBuyCount());
                }else {
                    jr.errorParam("来源字段错误",log);
                    return;
                }
                //同件产品,保存最新的分享码
                if(StringUtils.isBlank(shoppingCart.getShareCode())){
                    oldShoppingCart.setShareCode(shoppingCart.getShareCode());
                }

                //同件产品,保存最新的渠道码
                if(StringUtils.isBlank(shoppingCart.getShareCode())){
                    oldShoppingCart.setShareCode(shoppingCart.getShareCode());
                }
            }
            oldShoppingCart.setLastUpdated(new Date());

            //更新购物车
            oldShoppingCart = shoppingCartRepository.save(oldShoppingCart);
            if (null == oldShoppingCart) {
                jr.errorParam("操作不成功",log);
            }
            jr.setData(oldShoppingCart);
        };
        return doing.go(request, log);
    }
}
